import { defineStore } from "pinia";
import { ElMessage } from 'element-plus'
import { localCache } from '@/utils/cache'
import { LOGIN_TOKEN } from '@/global/constants'
import router from '@/router/index'

import {
  loginRequest,
  getUserInfoById,
  registerUser
} from '@/service/login/login'

interface LoginState {
  token: string
  userId: string
  name: string
  password: string
  avatarUrl: string
  nickname: string
  signature: string
  link: string
}

const useLoginStore = defineStore('login', {
  state: ():LoginState => ({
    token: '',
    userId: '',
    name:  '',
    password:  '',
    avatarUrl:  '',
    nickname:  '',
    signature:  '',
    link: ''
  }),
  actions: {
    async loginRequestAction(name: string, password: string) {
      await loginRequest(name, password).then(res => {
        // console.log(res)
        if(res.code == 200) {
          const id = res.id
          this.userId = id
          localCache.setCache('userId', id)
          const token = res.token 
          this.token = token
          localCache.setCache(LOGIN_TOKEN, token)
          localCache.setCache('routerPath', '/homePage')
          getUserInfoById(id).then(res => {
            // console.log(res)
            const name = res.name
            this.name = name
            localCache.setCache('name', name)

            const password = res.password
            this.password = password
            localCache.setCache('password', password)

            const avatarUrl = res.avatar_url
            this.avatarUrl = avatarUrl
            localCache.setCache('avatarUrl', avatarUrl)

            const nickname = res.nick_name
            this.nickname = nickname
            localCache.setCache('nickname', nickname)

            const signature = res.signature
            this.signature = signature
            localCache.setCache('signature', signature)

            const link = res.link
            this.link = link
            localCache.setCache('link', link)

              router.push('/')
          })
        } else {
          ElMessage({
            message: res.response.data,
            type: 'error',
          })
        }
      })
    },
    updateUserInfo() {
      this.name = localCache.getCache('name')

      this.password = localCache.getCache('password')

      this.avatarUrl = localCache.getCache('avatarUrl')

      this.nickname = localCache.getCache('nickname')
  
      this.signature = localCache.getCache('signature')

    },
    registerUserAction(user: any ={}) {
      registerUser(user).then(res => {
        console.log(res)
        if(res.code == 200 ) {
          ElMessage({type: 'success', message: res.msg})
        }else {
          ElMessage({type: 'error', message: res.response.data})
        }
      })
    }
  }
})

export default useLoginStore